package com.huizhonglm.diap.api;

import android.os.Handler;
import android.os.Message;

import com.alibaba.fastjson.JSON;
import com.bruce.common.utils.EmptyUtil;
import com.huizhonglm.diap.core.utils.LogUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.UUID;

/**
 * 上传工具类
 *
 * @author LiXiaolong
 * 支持上传文件和参数
 */

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-05-31 09:42
 */
public class Conn {
    private static Conn mInstance;

    private final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    private final String PREFIX = "--";
    private final String LINE_END = "\r\n";
    private final String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    private final String CHARSET = "utf-8"; // 设置编码

    private final int MSG_WHAT_SUCCESS = 11;
    private final int MSG_WHAT_FAILURE = 22;

    private final int REQUEST_SUCCESS = 1;// 上传成功
    private final int REQUEST_FAILURE = 2;// 服务器出错



    private HttpHandler mHandler;
    private HttpCallback mCallback;

    /**
     * 单例模式获取上传工具类
     * @return UploadUtil
     */
    public static Conn getInstance() {
        if (mInstance == null) {
            synchronized (Conn.class) {
                if (mInstance == null) {
                    mInstance = new Conn();
                }
            }
        }
        return mInstance;
    }

    private Conn() {
        mHandler = new HttpHandler(this);
    }

    public void post(final String apiName, final String url, final Map<String, String> param, HttpCallback callback){
        mCallback = callback;
        if (EmptyUtil.isEmpty(url)) {
            handleCallback(REQUEST_FAILURE, "接口地址为空");
            return;
        }
        new Thread(new Runnable() { //开启线程上传文件
            @Override
            public void run() {
                doPost(apiName, url, param);
            }
        }).start();
    }

    private void doPost(String apiName, String reqUrl, Map<String, String> param){
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

            if (!EmptyUtil.isEmpty(param)) {
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                StringBuilder sb;
                String params;
                for (String key : param.keySet()) {
                    sb = new StringBuilder();
                    String value = param.get(key);
                    sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                    sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
                    sb.append(value).append(LINE_END);
                    params = sb.toString();
                    dos.write(params.getBytes());
                }
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
            }

            /**
             * 获取响应码 200=成功 当响应成功，获取响应的流
             */
            int resCode = conn.getResponseCode();
            if (resCode == 200) {
                InputStreamReader isReader = new InputStreamReader(conn.getInputStream(), CHARSET);
                BufferedReader reader = new BufferedReader(isReader);
                String line;
                String result = "";
                while(null != (line = reader.readLine())){
                    result += line;
                }
                reader.close();
                conn.disconnect();
                printLog(apiName, reqUrl, param, result, false);
                sendMessage(MSG_WHAT_SUCCESS, result);
            } else {
                printLog(apiName, reqUrl, param, null, true);
                sendMessage(MSG_WHAT_FAILURE, "上传失败，服务器异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            printLog(apiName, reqUrl, param, null, true);
            sendMessage(MSG_WHAT_FAILURE, "上传失败，服务器异常");
        }
    }

    private void printLog(String apiName, String url, Map<String, String> params, String result, boolean isFailured){
        final String TAG = "DIAP_API";
        if (!EmptyUtil.isEmpty(params)) {
            LogUtil.print(TAG, "http :: [" + apiName + "] - request - " + url);
            LogUtil.print(TAG, "http :: [" + apiName + "] - request - " + params.toString());
        }
        if (isFailured) {
            LogUtil.print(TAG, "http :: [" + apiName + "] - response - failured");
        } else {
            if (EmptyUtil.isEmpty(result)) {
                LogUtil.print(TAG, "http :: [" + apiName + "] - response - result is null");
            } else {
                LogUtil.print(TAG, "http :: [" + apiName + "] - response - " + JSON.toJSON(result));
            }
        }
    }

    private void sendMessage(int what, String result){
        Message msg = new Message();
        msg.what = what;
        msg.obj = result;
        mHandler.sendMessage(msg);
    }

    private void handleMessage(Message msg) {
        String result = (String) msg.obj;
        switch (msg.what) {
            case MSG_WHAT_SUCCESS:
                handleCallback(REQUEST_SUCCESS, result);
                break;
            case MSG_WHAT_FAILURE:
                handleCallback(REQUEST_FAILURE, result);
                break;
        }
    }

    private void handleCallback(int resCode, String result){
        if (mCallback != null) {
            if (resCode == REQUEST_SUCCESS) {
                mCallback.onSuccess(result);
            } else {
                mCallback.onFailure(new Throwable(result));
            }
        }
    }

    public static class HttpHandler extends Handler {
        WeakReference<Conn> wrf;

        public HttpHandler(Conn cls) {
            wrf = new WeakReference<>(cls);
        }

        @Override
        public void handleMessage(Message msg) {
            Conn upload = wrf.get();
            if (upload != null) {
                upload.handleMessage(msg);
            }
        }
    }
}
